package springboot.file.demo.util;

import com.obs.services.ObsClient;
import com.obs.services.exception.ObsException;
import com.obs.services.model.*;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import springboot.file.demo.common.Result;
import springboot.file.demo.properties.HuaweiCloudProperties;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.Date;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @Author: jxm
 * @Description: 上传图片工具类
 * @Date: 2022/1/20 11:33
 * @Version: 1.0
 */
@Slf4j
@Component
public class UploadUtils {

    @Autowired
    HuaweiCloudProperties cloudProperties;

    //文件大小字节
    private static long fileSize = 2*1024*1024; //2M

    public Result upload(MultipartFile file){
        //获取源文件名称
        String originalFilename = file.getOriginalFilename();
        //获取文件后缀
        String suffix = originalFilename.substring(originalFilename.lastIndexOf(".")+1, originalFilename.length());

//        if(!suffix.equalsIgnoreCase("png") && !suffix.equalsIgnoreCase("jpeg") &&
//                !suffix.equalsIgnoreCase("bmp") && !suffix.equalsIgnoreCase("jpg")&&
//                !suffix.equalsIgnoreCase("gif")){
//            log.info("图片格式不正确:"+suffix);
//            return Result.build(400,"图片格式不正确");
//        }
        if(!suffix.equalsIgnoreCase("xlsx") && !suffix.equalsIgnoreCase("xls") &&
                !suffix.equalsIgnoreCase("doc") && !suffix.equalsIgnoreCase("docx")&&
                !suffix.equalsIgnoreCase("pdf") && !suffix.equalsIgnoreCase("txt")){
            log.info("文件格式不正确:"+suffix);
            return Result.build(400,"文件格式不正确");
        }

        //获取文件大小
        long size = file.getSize();
        if(size > fileSize){
            log.info("文件大小不能大于2M:"+size);
            return Result.build(400,"文件大小不能大于2M");
        }
        InputStream in=null;
        ObsClient obsClient = null;
        try {
            //获取流对象
            in= file.getInputStream();
            // 创建ObsClient实例
            obsClient = new ObsClient(cloudProperties.getAk(), cloudProperties.getSk(), cloudProperties.getEndPoint());
            //保存文件目录
            String dir = cloudProperties.getDir()+TimeUtils.getCurrDate()+"/";
            //保存文件名
            String fileName = new Date().getTime() + UUID.randomUUID().toString().replace("-", "").substring(0, 6);
            //保存文件
            PutObjectRequest request = new PutObjectRequest();
            request.setBucketName(cloudProperties.getBucketName());
            request.setObjectKey(dir+fileName+"."+suffix);
            request.setInput(in);
            PutObjectResult putObjectResult = obsClient.putObject(request);
            return Result.ok(cloudProperties.getDomainName()+dir+fileName+"."+suffix);
        }catch (IOException e){
            e.printStackTrace();
            log.info("获取文件流失败");
        }catch (ObsException e){
            log.info("上传文件异常");
            e.printStackTrace();
        }finally {
            if(obsClient != null){
                try {
                    obsClient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return Result.build(400,"上传文件失败");
    }


    /**
     * 下载文件
     *
     * @param fileName 文件名称
     * @param fileType 文件路径
     * @return
     */
    public Result getDownloadUrl(String fileName, String fileType) {
        ObsClient obsClient = null;
        obsClient = new ObsClient(cloudProperties.getAk(), cloudProperties.getSk(), cloudProperties.getEndPoint());
        // URL有效期，3600秒.5分钟
        long expireSeconds = 3600L;
        String objectName = cloudProperties.getDir()+TimeUtils.getCurrDate()+"/"+fileName;
        TemporarySignatureRequest request = new TemporarySignatureRequest(HttpMethodEnum.GET, expireSeconds);
        request.setBucketName(cloudProperties.getBucketName());
        request.setObjectKey(objectName);
        TemporarySignatureResponse response = obsClient.createTemporarySignature(request);
        return Result.ok(response.getSignedUrl());
    }

    /**
     * 步骤：
     * 1.前端传文件 id
     * 2.根据id查找对应文件对象
     * 3.截取对应上传文件名称（是存在对象存储服务器的）
     * String fileName = realPath.substring(realPath.lastIndexOf("\\") + 1);
     * String image = imgUrl.substring(imgUrl.lastIndexOf("/")+1);
     * 4.获取文件名称（自己存的文件中文名）
     *
     *
     * @param fileName
     * @param resp
     * @throws Exception
     */
    public void downLoad(String fileName, HttpServletResponse resp) throws Exception{
        String endPoint = cloudProperties.getEndPoint();
        String ak = cloudProperties.getAk();
        String sk = cloudProperties.getSk();

        // 创建ObsClient实例
        final ObsClient obsClient = new ObsClient(ak, sk, endPoint);

        String objectName = cloudProperties.getDir()+TimeUtils.getCurrDate()+"/"+fileName;
        ObsObject obsObject = obsClient.getObject(cloudProperties.getBucketName(), objectName);
        // 读取对象内容
        System.out.println("Object content:"+obsObject);

        //3.设置想办法让浏览器能够支持下载我们需要的东西
        resp.setHeader("Content-disposition","attachment;filename="+ URLEncoder.encode(fileName,"utf-8"));

        InputStream input = obsObject.getObjectContent();
        byte[] b = new byte[1024];
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        int len;
        while ((len=input.read(b)) != -1){
            bos.write(b, 0, len);
        }

        //获取输出流
        ServletOutputStream out = resp.getOutputStream();

        out.write(bos.toByteArray());

        out.close();
        bos.close();
        input.close();

    }


}
